/***************************************************************************
 //* Foxit Software Inc.
 //* Copyright(C) 2005-2012, all rights reserved.
 //*
 //* The following code is copyrighted and contains proprietary information
 //* and trade secrets of Foxit Software Inc.                                                      *
 ***************************************************************************/
//常用对话框;
define(function (require, exports, module) {  

    var _alertDlgHtml = "",
        _alertDlg = null,
        _isAlertDlgInitialized = false,

        _confirmDlgHtml = "",
        _confirmDlg = null,
        _isConfirmDlgInitialized = false,

        _confirmPasswordDlgHtml = "",
        _isConfirmPasswordDlgInitialized = false,
        _confirmPasswordDlg = null,

        _textCopyDlgHtml = "",
        _textCopyDlg = null,
        _isTextCopyDlgInitialized = false,

        _loadingHtml = "",
        _loadingDlg = null,
        _isLoadingDlgInitialized = false,

        _defaultDlgTitle = null;    
    

    function _getDefaultTitle(readerApp){
        //if(_defaultDlgTitle != null){
        //    return _defaultDlgTitle;
        //}
        _defaultDlgTitle = readerApp.getOptions().defaultDialogTitle;
        if(_defaultDlgTitle == null){
            _defaultDlgTitle = i18n.t("CommonDialog.DefaultDlgTitle");
        }
    }


    function _popupTextCopyDlg(readerApp,text2Copy, title, btnTitle, closeCallback) {
        _getDefaultTitle(readerApp);
        var textAreaId = "fwrTextCopyArea";
        var textCopyDlgId = "fwrTextCopyDlg";
        var closeButtonId = "fwrTextCopyClose";
        var titleId = "fwrTextCopyTitle";
        var $title = null;
        var $closeBtn = null;
        var $textArea = null;
        if (!_isTextCopyDlgInitialized) {
            var inputText = "";
            if (WebPDF.Environment.mobile){
                inputText = "<textarea id='" + textAreaId + "' type='text' value='' />";
            }
            else {
                inputText = "<textarea id='" + textAreaId + "' type='text' value=''  readonly='readonly'/>";
            }
            readerApp.addIgnoreMouseEventClass("fwr-text-copy-dlg");
            _textCopyDlgHtml = "<div id='" + textCopyDlgId + "' class='fwr-modal fwr-hide fwr-fade fwr-in fwr-text-copy-dlg'>" +
                "<div class='fwr-modal-header'>" +
                "<button class='close' webpdf-data-dismiss='modal'></button>" +
                "<h4 id='" + titleId + "'>Text Copy</h4>" +
                "</div>" +
                "<div class='fwr-modal-body'>" +
                "<div >" +
                "<span data-i18n='CommonDialog.TextCopyLimitMsg'>Current browser is not able to copy the text directly. Please copy the text manually.</span>" +
                "</div>" +
                inputText +
                "</div>" +
                "<div class='fwr-modal-footer'>" +
                "<button id='" + closeButtonId + "' class='btn btn-primary pull-left'  webpdf-data-dismiss='modal' data-i18n='CommonDialog.DefaultCloseBtnTitle'>Close</button>" +
                "</div>" +
                "</div>";
            $('#' + readerApp.getMainFrameId()).append(_textCopyDlgHtml);
            _textCopyDlg = $("#" + textCopyDlgId);
            _isTextCopyDlgInitialized = true;
        }
        if (!_textCopyDlg) {
            return;
        }
        $title = $("#" + titleId);
        $closeBtn = $("#" + closeButtonId);
        $textArea = $("#" + textAreaId);
        if (!title) {
            title = _defaultDlgTitle;
        }
        $title.html(title);
        if ($.isFunction(closeCallback)) {
            _textCopyDlg.off('hidden.bs.webpdf-modal').on('hidden.bs.webpdf-modal', function () {
                closeCallback();
            });
        }

        $textArea.val(text2Copy);

        if (!btnTitle)  {
            btnTitle = i18n.t("CommonDialog.DefaultCloseBtnTitle");
        }
        $closeBtn.text(btnTitle);
        _textCopyDlg.webPDFModal({keyboard:false, backdrop:"static", manager:"#"+readerApp.getMainFrameId()});
        _textCopyDlg.focus();
        if (WebPDF.Environment.mobile) {
            $textArea.off('touchstart').on('touchstart', function () {
                this.setSelectionRange(0, $textArea.val().length);
                $textArea.focus();
                return false;
            });
            $textArea.trigger('touchstart');
        }
        else {
            $textArea.focus();
            $textArea.select();
        }
    }

    WebPDF.waiting = function (readerApp) {
      
        _getDefaultTitle(readerApp);
        var waitingDlgId = "LoadingDlg";
        if (!_isLoadingDlgInitialized) {
            readerApp.addIgnoreMouseEventClass("fwr-ajax-loading");
            _loadingHtml =  "<div id='" + waitingDlgId + "' class='fwr-modal fwr-hide fwr-fade fwr-in fwr-ajax-loading' style='padding:0;'>" +
                "<span class='fwr-ajax-loading-text' data-i18n='ProgressBar.Loading'>Loading...</span>" +
                "</div>";
            _loadingDlg = $(_loadingHtml);
            _isLoadingDlgInitialized = true;
        }
        if (!_loadingDlg){
            return;
        }
        _loadingDlg.i18n();
        _loadingDlg.webPDFModal({keyboard:false, backdrop:"static",manager:"#"+readerApp.getMainFrameId()});
        var $backdrop = $(".fwr-modal-backdrop");
        if($backdrop.length > 0){
            $backdrop.addClass("fwr-modal-backdrop-loading");
        }
        var $viewer = $("#" + readerApp.getMainFrameId());
        $viewer.addClass('fwr-doc-viewer-loading');
    };

    WebPDF.closeWaiting = function (readerApp) {
        _loadingDlg && _loadingDlg.webPDFModal("hide");
        var $viewer = $("#" + readerApp.getMainFrameId());
        $viewer.removeClass('fwr-doc-viewer-loading');
    };

    /**
     * @description Popup a alert dialog.
     * @param {WebPDF.ReaderApp} readerApp The current app instance
     * @param {String} title  Title of the dialog, if this parameter is null or empty, default title will be used.
     * @param {String} msg Message of the dialog.
     * @param {String} btnTitle Title of “OK” button, if this parameter is null or empty, default title will be used.
     * @param {Function} closeCallback  Triggered when the alert dialog is about to close.
     * @param {Boolean} isAutoClose  Whether auto close the tooltip.
     */
    WebPDF.alert = function (readerApp,title, msg, btnTitle, closeCallback, isAutoClose) {
        /*if (WebPDF.Environment.mobile) {
         var tooltipId = "fwr_mobile_tooltip";
         if (!_isAlertDlgInitialized) {
         var toolTipDivHtml = "<div id='" + tooltipId + "'></div>";
         var $body = $('body');
         $body.append(toolTipDivHtml);
         }
         _isAlertDlgInitialized = true;
         var jqTooltip = $('#' + tooltipId);
         jqTooltip.tinytooltip({
         message: function () {
         return msg;
         },
         hover: false
         });
         if (!isAutoClose) {
         isAutoClose = false;
         }
         jqTooltip.trigger('showtooltip');
         if (isAutoClose)
         setTimeout(function () {
         jqTooltip.trigger('hidetooltip');
         }, WebPDF.Config.defaults.TooltipTimeout);
         }
         else {*/
        var alertDlgId = "fwrAlertDlg";
        var closeButtonId = "fwrAlertDialogCloseBtn";
        var $closeBtn = null;
        var alertMsgId = "fwrAlertDialogMsgHolder";
        var $msg = null;
        var titleId = "fwrAlertDialogTitle";
        var $title = null;
        _getDefaultTitle(readerApp);
        if (!_isAlertDlgInitialized) {
            readerApp.addIgnoreMouseEventClass("fwr-alert");
            _alertDlgHtml =
                "<div id='" + alertDlgId + "' class='fwr-modal fwr-hide fwr-fade fwr-in fwr-alert' style='display: none;'>" +
                "<div class='fwr-modal-header'>" +
                "<a class='close' webpdf-data-dismiss='modal'></a>" +
                "<h4 id='" + titleId + "'>Foxit Web PDF</h4>" +
                "</div>" +
                "<div class='fwr-modal-body'>" +
                "<p id='" + alertMsgId + "'>Msg Body" +
                "</p>" +
                "</div>" +
                "<div class='fwr-modal-footer' >" +
                "<button href='#' id='" + closeButtonId + "' class='btn btn-primary pull-left' style=' width:42px' webpdf-data-dismiss='modal' data-i18n='CommonDialog.DefaultOKBtnTitle'>Close</button>" +
                "</div>" +
                "</div>";
            $('#' + readerApp.getMainFrameId()).append(_alertDlgHtml);
            _alertDlg = $("#" + alertDlgId);

            _isAlertDlgInitialized = true;
        }
        if (!_alertDlg) {
            return;
        }
        $closeBtn = $("#" + closeButtonId);
        $title = $("#" + titleId);
        $msg = $("#" + alertMsgId);
        $closeBtn.off('click').on("click", function (e) {
            _alertDlg.webPDFModal('hide');
            e.stopPropagation();
        });
        if (!title) {
            title = _defaultDlgTitle;
        }
        $title.html(title);
        if (!msg){
            msg = "";
        }
        $msg.html(msg);
        if (!btnTitle){
            btnTitle = i18n.t("CommonDialog.DefaultOKBtnTitle");
        }
        $closeBtn.text(btnTitle);
        if ($.isFunction(closeCallback)) {
            _alertDlg.off('hidden.bs.webpdf-modal').on('hidden.bs.webpdf-modal', function () {
                closeCallback();
            });
        }
        _alertDlg.i18n();
        _alertDlg.webPDFModal({keyboard:false, backdrop:"static",manager:"#"+readerApp.getMainFrameId()});
        _alertDlg.focus();
    };

    /**
     * @description Close the alert dialog.
     */
    WebPDF.endAlert = function () {
        _alertDlg && _alertDlg.webPDFModal("hide");
    };

    /**
     * @description Popup a confirm dialog.
     * @param {WebPDF.ReaderApp} readerApp The current app instance.
     * @param {String} title  Title of the dialog, if this parameter is null or empty, default title will be used.
     * @param {String} msg Of the dialog.
     * @param {String} btnOkTitle Title of “OK” button, if this parameter is null or empty, default title will be used.
     * @param {String} btnCancelTitle Title of “Cancel” button, if this parameter is null or empty, default title will be used.
     * @param {Function} callback Triggered when the confirm dialog is about to close.
     */
    WebPDF.confirm = function (readerApp,title, msg, btnOkTitle, btnCancelTitle, callback, width, height) {
        _getDefaultTitle(readerApp);
        var confirmDlgId = "fwrConfirmDlg";
        var confirmMsgId = "fwrConfirmDlgMsgHolder";       
        var okBtnId = "fwrConfirmDlgOkBtn";
        var cancelBtnId = "fwrConfirmDlgCancelBtn";      
        var titleId = "fwrConfirmDialogTitle";
      
        if (!_isConfirmDlgInitialized) {
            readerApp.addIgnoreMouseEventClass("fwr-confirm");
            _confirmDlgHtml = "<div id='" + confirmDlgId + "' class='fwr-modal fwr-hide fwr-fade fwr-in fwr-confirm'>" +
                "<div class='fwr-modal-header'>" +
                "<a class='close' webpdf-data-dismiss='modal'></a>" +
                "<h4 id='" + titleId + "'>Foxit Web PDF</h4>" +
                "</div>" +
                "<div class='fwr-modal-body'>" +
                "<p id='" + confirmMsgId + "' >Body Msg</p>" +
                "</div>" +
                "<div class='fwr-modal-footer'>" +
                "<a href='#' type='button' class='btn btn-primary pull-left' style='width:42px'  id='" + okBtnId + "' webpdf-data-dismiss='modal' data-i18n='CommonDialog.DefaultOKBtnTitle'>OK</a>  " +
                "<a href='#' type='button' class='btn btn-default pull-left' style='margin-left:10px' id='" + cancelBtnId + "' webpdf-data-dismiss='modal' data-i18n='CommonDialog.DefaultCancelBtnTitle'>Cancel</a>" +
                "</div>" +
                "</div>";
            $('#' + readerApp.getMainFrameId()).append(_confirmDlgHtml);
            _confirmDlg = $("#" + confirmDlgId);          
            
                
            _isConfirmDlgInitialized = true;
        }
        if (!_confirmDlg){
            return;
        }              
        
        var $title = _confirmDlg.find("#" + titleId);
        var $msg =   _confirmDlg.find("#" + confirmMsgId);
        var $okBtn = _confirmDlg.find("#" + okBtnId);
        var $cancelBtn = _confirmDlg.find("#" + cancelBtnId);
        if (!title) {
            title = _defaultDlgTitle;
        }
        $title.html(title);
        
        if (!msg){
            msg = "";
        }
        $msg.html(msg);
        
        if (!btnOkTitle){
            btnOkTitle = i18n.t("CommonDialog.DefaultOKBtnTitle");
        }
        if (!btnCancelTitle) {
            btnCancelTitle = i18n.t("CommonDialog.DefaultCancelBtnTitle");
        }
        $okBtn.text(btnOkTitle);
        $cancelBtn.text(btnCancelTitle);

        if (!$.isFunction(callback)) {
            callback = function () {
                _confirmDlg.webPDFModal("hide");
            };
        }

        $okBtn.text(btnOkTitle).off('click').on('click', function () {
            callback(true);
        });
        $cancelBtn.text(btnCancelTitle).off('click').on('click', function () {
            callback(false);
        });
        _confirmDlg.i18n();
        _confirmDlg.webPDFModal({width:width, height:height, keyboard:false, backdrop:"static",manager:"#"+readerApp.getMainFrameId()});
        _confirmDlg.focus();
    };

    /**
     * @description Close the confirm dialog.
     */
    WebPDF.endConfirm = function () {
        _confirmDlg &&  _confirmDlg.webPDFModal("hide");
    };

    var passwordInputId = "fwrPasswordDlgPasswordInput";
    var $passwordInput = null;
    WebPDF.confirmPassword = function (readerApp,title, msg, callback, btnOkTitle, btnCancelTitle,enterPasswordTip) {
        _getDefaultTitle(readerApp);
        var confirmPsdDlgId = "fwrPasswordDlg";
        var confirmMsgId = "fwrPasswordDlgMsgHolder";
        var errorInfoLabelId = "fwrPasswordDlgErrorLabel";
        var okBtnId = "fwrPasswordDlgOkBtn";
        var cancelBtnId = "fwrPasswordDlgCancelBtn";
        var $okBtn = null;
        var $cancelBtn = null;
        var titleId = "fwrPasswordDialogTitle";
        var $title = null;
        var $errorInfo = null;
        var $msg = null;
        var psdDialogClass= "fwr-password-confirm";
        var psdInputLableId = "fwrPasswordDlgInputLabel";
        if (WebPDF.Environment.mobile) {
            psdDialogClass = "fwr-password-confirm-mobile";
        }

        if (!_isConfirmPasswordDlgInitialized) {
            readerApp.addIgnoreMouseEventClass("fwr-password-confirm");
            readerApp.addIgnoreMouseEventClass("fwr-password-confirm-mobile");
            _confirmPasswordDlgHtml = "<div id='" + confirmPsdDlgId + "' class='fwr-modal fwr-hide fwr-fade fwr-in " + psdDialogClass + "'>" +
                "<div class='fwr-modal-header'>" +
                "<a class='close' webpdf-data-dismiss='modal'></a>" +
                "<h4 id='" + titleId + "'>Foxit Web PDF</h4>" +
                "</div>" +
                "<div class='fwr-modal-body'>" +
                "<div id='' class='fwr-password-warn' data-i18n='ParseError.EnterPassword' style='font-size:13px'>password</div>" +
                "<div class='fwr-password-block' style='margin-top:10px'> " +
                "<span class='fwr-password-lable' id='"+ psdInputLableId +"' >Password:</span>" +
                "<input type='password'  id='" + passwordInputId + "' name='fwr-password' />" +
                "</div>" +
                "<div class='error-info'>" +
                "<span id='" + errorInfoLabelId + "'>Error code</span>"+
                "</div>" +
                "</div>" +
                "<div class='fwr-modal-footer'>" +
                "<button href='#' type='button' class='btn btn-primary pull-left' style='width:42px'   id='" + okBtnId + "' data-i18n='CommonDialog.DefaultOKBtnTitle'>OK</button> " +
                "<button href='#' type='button' class='btn btn-default pull-left' style='margin-left:10px'  id='" + cancelBtnId + "' webpdf-data-dismiss='modal' data-i18n='CommonDialog.DefaultCancelBtnTitle'>Cancel</button>" +
                "</div>" +
                "</div>";

            $('#' + readerApp.getMainFrameId()).append(_confirmPasswordDlgHtml);
            _confirmPasswordDlg = $("#" + confirmPsdDlgId);
            $passwordInput = $("#" + passwordInputId);
            $passwordInput.off('keyup').on('keyup', function (event) {
                var theEvent = event || window.event;
                var code = theEvent.keyCode || theEvent.which || theEvent.charCode; //获取键盘code
                if (code == '13') {
                    $okBtn.click();
                }
            });
            _confirmPasswordDlg.on("shown",function(){
                if(!WebPDF.Environment.mobile)
                {
                    $passwordInput.focus();
                }
            });
            _isConfirmPasswordDlgInitialized = true;
        }
        if (!_confirmPasswordDlg) {
            return;
        }
        $okBtn = $("#" + okBtnId);
        $cancelBtn = $("#" + cancelBtnId);
        $cancelBtn.off('click').on('click', function () {
            _confirmPasswordDlg.webPDFModal("hide");
        });
        $passwordInput = $("#" + passwordInputId);
        $title = $("#" + titleId);
        $msg = $("#" + confirmMsgId);
        $errorInfo = $("#" + errorInfoLabelId);        
        $passwordInput.empty();
        $inputLabel = $("#" + psdInputLableId);
        //data-i18n='CommonDialog.EnterPasswordTip'
        if(!enterPasswordTip){
        	enterPasswordTip = i18n.t("CommonDialog.EnterPasswordTip");
        }
        if (WebPDF.Environment.mobile) {
        	enterPasswordTip = i18n.t("CommonDialog.MoblieEnterPasswordTip");
	        $passwordInput.off('focus').on('focus',function(){
	        	$inputLabel.hide();
	        });
	        $passwordInput.off('blur').on('blur',function(){
	        	$inputLabel.show();
	        });
        }
        $inputLabel.html(enterPasswordTip);
        $errorInfo.empty();
        if (!title) {
            title = _defaultDlgTitle;
        }
        $title.html(title);
        if (!msg){
            msg = "";
        }
        $msg.html(msg);
        if (!btnOkTitle){
            btnOkTitle = i18n.t("CommonDialog.DefaultOKBtnTitle");
        }
        if (!btnCancelTitle){
            btnCancelTitle = i18n.t("CommonDialog.DefaultCancelBtnTitle");
        }
        $cancelBtn.text(btnCancelTitle);
        if (!$.isFunction(callback)) {
            callback = function () {
                _confirmPasswordDlg.webPDFModal("hide");
            };
        }
        $okBtn.text(btnOkTitle).off('click').on('click', function () {
            callback($passwordInput, $errorInfo);
        });
        _confirmPasswordDlg.i18n();
        _confirmPasswordDlg.webPDFModal({keyboard:false, backdrop:"static",manager:"#"+readerApp.getMainFrameId()});
       // $passwordInput.focus();
    };


    WebPDF.endConfirmPassword = function () {
        if(_confirmPasswordDlg){
            $passwordInput.empty().val("");
            _confirmPasswordDlg.webPDFModal("hide");
        }
    };

    function _saveDataToFirefoxClipboard(text) {
        if (window.netscape) {   //Firefox浏览器
            try {
                netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
            }
            catch (ex) {
                console.error(ex);
                return false;
            }
            var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);
            if (!clip) return;
            var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);
            if (!trans) return;
            trans.addDataFlavor('text/unicode');
            var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
            str.data = text;
            trans.setTransferData("text/unicode", str, text.length * 2);
            var clipboardId = Components.interfaces.nsIClipboard;
            if (!clip) return false;
            clip.setData(trans, null, clipboardId.kGlobalClipboard);
            return true;
        }
    }

    WebPDF.copyText = function (readerApp,text2Copy, title, btnTitle, closeCallback, width) {
        try {
            if (window.clipboardData) {
                var bClip = window.clipboardData.setData("Text", text2Copy);
                if (!bClip) {
                    _popupTextCopyDlg(readerApp,text2Copy, title, btnTitle, closeCallback, width);
                    return false;
                }
            }
            else if (window.netscape) {
                if (!_saveDataToFirefoxClipboard(text2Copy)) {
                    _popupTextCopyDlg(readerApp,text2Copy, title, btnTitle, closeCallback, width);
                    return false;
                }
            }
            else {
                _popupTextCopyDlg(readerApp,text2Copy, title, btnTitle, closeCallback, width);
                return false;
            }
        }
        catch (ex) {
            console.error(ex);
            _popupTextCopyDlg(readerApp,text2Copy, title, btnTitle, closeCallback, width);
            return false;
        }
        return true;
    };

    WebPDF.endTextCopyDlg = function () {
        _textCopyDlg && _textCopyDlg.dialog('close');
    };
});
